<?php
/**
 * Created by Administrator
 * User: longli
 * Date: 2020/08/12
 * Time: 18:20
 * @link http://www.lmterp.cn
 */

namespace app\common\service\product;


use app\common\library\Tools;
use app\common\model\Account;
use app\common\model\Category;
use app\common\model\Product;
use app\common\model\ProductPlatformSku;
use app\common\model\ProductPurchase;
use app\common\model\ProductStore;
use app\common\service\BaseService;

class PlatformService extends BaseService
{
    /**
     * 通过平台 sku 获取内部 sku, 如果有则返回内部 sku， 否则返回平台 sku
     * @param string $psku
     * @date 2020/08/12
     * @author longli
     * @return string
     */
    public function getSkuByPlatformSku($psku = '')
    {
        $obj = ProductPlatformSku::getByPlatformSku($psku);
        return !empty($obj) ? $obj->sku : $psku;
    }

    /**
     * 生成平台唯一 sku
     * @param int $num 生成的数量
     * @date 2020/08/12
     * @author longli
     * @return string|string[]
     */
    public function generatePlatformSku($num = 1)
    {
        if($num < 1) return "";
        $ret = [];
        $step = $num;
        while($step--)
        {
            do
            {
                $psku = Tools::getRandStr(mt_rand(8, 10), 2);
            }while(in_array($psku, $ret) || ProductPlatformSku::hasPlatformSku($psku));
            $ret[] = $psku;
        }
        if($num == 1) return $ret[0];
        return $ret;
    }

    /**
     * 通过变体 id 生成平台SKU
     * @param int $accountId 账号id
     * @param int[] $storeIds 变体 id
     * @param bool $force 如果存在是否再次生成，默认不生成
     * @return bool
     * @date 2020/09/15
     * @author longli
     */
    public function generateSkuByStoreId($accountId, $storeIds = [], $force = false)
    {
        if(!is_array($storeIds)) $storeIds = explode(',', $storeIds);
        $pskus = $this->generatePlatformSku(count($storeIds));
        if(!is_array($pskus)) $pskus = [$pskus];
        $data = [];
        foreach(ProductStore::field("product_id,sku,store_id")->where("store_id", "in", $storeIds)->select() as $k => $item)
        {
            if(!$force && ProductPlatformSku::hasByStoreAccount($accountId, $item->store_id)) continue;
            $data[] = [
                'product_id'   => $item->product_id,
                'store_id'     => $item->store_id,
                'account_id'   => $accountId,
                "platform_sku" => $pskus[$k],
                "sku"          => $item->sku,
            ];
        }
        try
        {
            if(!empty($data)) ProductPlatformSku::insertAll($data);
            return true;
        }catch (\Exception $e)
        {
            return false;
        }
    }

    /**
     * 通过已生的平台SKU, 再次生成
     * @param array $pid
     * @return bool
     * @date 2020/09/16
     * @author longli
     */
    public function generateSkuByPid($pid = [])
    {
        if(!is_array($pid)) $pid = explode(',', $pid);
        $data = [];
        foreach(ProductPlatformSku::where("pid", "in", $pid)->select() as $item)
        {
            $t = Tools::visibleArray(['product_id', 'store_id', 'sku', 'account_id'], $item->toArray());
            $t['platform_sku'] = $this->generatePlatformSku(1);
            $data[] = $t;
        }
        if(empty($data)) return false;
        return ProductPlatformSku::limit(500)->insertAll($data) > 0;
    }


    public function search($search = [])
    {
        $psWhere = [];
        $model = ProductPlatformSku::alias("ps")
            ->field(["ps.*", "p.product_id", "p.name_ch", "p.name_ch", "p.category_id"])
            ->join(Product::getTable() . " p", "p.product_id=ps.product_id")
            ->with(["store", "account"]);
        if(!empty($search['platform_id']))
        {
            $model->where("account_id", "in", function($query)use($search)
            {
                $query->table(Account::getTable())->where("platform_id", $search['platform_id'])->field("account_id");
            });
        }
        if(!empty($search['category_id']))
        {
            $cateId = array_column(Category::getAllSon($search['category_id'])->toArray(), 'cate_id');
            $model->where("p.category_id", "in", $cateId);
        }
        if(!empty($search['producer_name']))
        {
            $model->where("ps.product_id", "in", function($query) use($search)
            {
                $query->table(ProductPurchase::getTable())->field("product_id")->where("producer_name", $search['producer_name']);
            });
        }
        if(!empty($search['start_date'])) $psWhere = array_merge($psWhere, $this->parseLayuiRangeDate('ps.create_time', $search['start_date']));
        if(isset($search['create_date'])) $psWhere = array_merge($psWhere, $this->parseScopeDateToWhere("ps.create_time", $search['create_date']));
        if(!empty($search['account_id'])) $psWhere[] = ['ps.account_id', '=', $search['account_id']];
        if(!empty($search['sku'])) $psWhere[] = ['ps.sku', 'like', "{$search['sku']}%"];
        if(!empty($search['platform_sku'])) $psWhere[] = ["ps.platform_sku", "like", "{$search['platform_sku']}%"];
        if(!empty($search['name_ch'])) $psWhere[] = ["p.name_ch", 'like', "%{$search['name_ch']}%"];
        if(!empty($search['name_en'])) $psWhere[] = ["p.name_en", 'like', "%{$search['name_en']}%"];

        $sort = "ps.pid desc";
        if(!empty($search['sort'])) $sort = "p.{$search['sort']}";
        return $model->order($sort)->where($psWhere)->paginate($this->getPageSize($search));
    }
}